package com.example.piece.ui.activity

import android.app.Activity
import android.graphics.Picture
import android.net.http.SslError
import android.os.Build
import android.os.Bundle
import android.os.Handler
import android.text.TextUtils
import android.util.Log
import android.view.View
import android.webkit.*
import androidx.databinding.ViewDataBinding
import com.therouter.router.Autowired
import com.therouter.router.Route
import com.example.base.ext.getViewModel
import com.example.base.ui.activity.BaseActivity
import com.example.piece.R
import com.example.piece.constant.Key
import com.example.piece.constant.RoutePath
import com.example.piece.databinding.ActivityH5Binding

@Route(path = RoutePath.MAIN_H5_ACTIVITY)
class H5Activity : Layer3Activity<ActivityH5Binding,ViewDataBinding>() {
    override val title: String
        get() = H5_TITLE

    override val isTransparentStatusBar: Boolean = true
    override val isLockPortrait: Boolean = true
    override val statusBarAlpha: Int = 0
    override val isDarkMode: Boolean = true
    override val isFitsSystemWindows: Boolean = true
    override val leftIcon1Res: Int = R.drawable.ic_back


    override fun onClickLeftIcon1(view: View) {
        onBackPressed()

    }

    @JvmField
    @Autowired(name = Key.DataKey.H5_URL)
    var H5_URL: String = ""

    @JvmField
    @Autowired(name = Key.DataKey.H5_TITLE)
    var H5_TITLE: String = ""

    override val centerLayoutRes: Int
        get() =R.layout.activity_h5




    override fun initData(savedInstanceState: Bundle?) {
        super.initData(savedInstanceState)

        Log.e("H5_URL", H5_URL)

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            mCenterViewBinding?.wvH5?.getSettings()
                ?.setMixedContentMode(android.webkit.WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);

        }


        mCenterViewBinding?.wvH5?.setWebChromeClient(object : WebChromeClient() {
            override fun onProgressChanged(view: WebView, newProgress: Int) {
                try {
                    if (newProgress >= 100) {
                        mCenterViewBinding?.pbH5?.setVisibility(View.GONE)
                    } else {
                        if (mCenterViewBinding?.pbH5?.getVisibility() != View.VISIBLE) {
                            mCenterViewBinding?.pbH5?.setVisibility(View.VISIBLE)
                        }
                        mCenterViewBinding?.pbH5?.setProgress(newProgress)
                    }
                } catch (e: Exception) {
                }
                super.onProgressChanged(view, newProgress)
            }
        })
        mCenterViewBinding?.wvH5?.let { initWebViewSetting(it) }
        mCenterViewBinding?.wvH5?.addJavascriptInterface(JavaScriptinterface(this), "AiDingFangJSBridge")
        mCenterViewBinding?.wvH5?.setWebViewClient(object : WebViewClient() {
            override fun shouldOverrideUrlLoading(
                view: WebView,
                request: WebResourceRequest
            ): Boolean {
                return super.shouldOverrideUrlLoading(view, request)
            }

            override fun onReceivedSslError(
                view: WebView,
                handler: SslErrorHandler,
                error: SslError
            ) {
                handler.proceed()
            }

            override fun onPageFinished(view: WebView, url: String?) {
                super.onPageFinished(view, url)
                val title = view.title
                if (!TextUtils.isEmpty(title)) {
                    baseViewModel.title.value = title

                } else {
                    baseViewModel.title.value = title


                }
            }
        })
        mCenterViewBinding?.wvH5?.setPictureListener(object : WebView.PictureListener {
            override fun onNewPicture(view: WebView?, arg1: Picture?) {
                val title = view?.title
                if (!TextUtils.isEmpty(title)) {
                    baseViewModel.title.value = title
                } else {
                    baseViewModel.title.value = title

                }
            }
        })
        mCenterViewBinding?.wvH5?.setWebViewClient(object : WebViewClient() {
            override fun onReceivedSslError(
                view: WebView,
                handler: SslErrorHandler,
                error: SslError
            ) {
                handler.proceed()
            }
        })
        mCenterViewBinding?.wvH5?.requestFocusFromTouch()
        Log.e("loge", H5_URL)
        mCenterViewBinding?.wvH5?.loadUrl(H5_URL)


    }


    class JavaScriptinterface     //}
        (var context: Activity) {
        private val mHandler: Handler? = null

        /**
         * 与js交互时用到的方法，在js里直接调用的
         */
        @JavascriptInterface
        fun closeWindow() {


            /*  mHandler.post(new Runnable() {
                public void run() {
                    //appView.loadUrl("javascript:wave()");*/
            context.finish()
        } // });
    }


    private fun initWebViewSetting(a: WebView) {
        a.settings.layoutAlgorithm = WebSettings.LayoutAlgorithm.SINGLE_COLUMN
        a.settings.loadWithOverviewMode = true
        a.settings.useWideViewPort = true
        a.settings.loadsImagesAutomatically = true
        a.settings.saveFormData = false
        a.settings.userAgentString = a.settings.userAgentString + "sm-bbs"
        a.isVerticalScrollBarEnabled = false
        a.settings.setSupportZoom(false)
        a.settings.javaScriptEnabled = true
        a.settings.javaScriptCanOpenWindowsAutomatically = true
        a.settings.pluginState = WebSettings.PluginState.ON
        a.settings.builtInZoomControls = false
        a.settings.domStorageEnabled = true
        a.settings.setSupportMultipleWindows(true)
        a.settings.cacheMode = WebSettings.LOAD_NO_CACHE
        a.settings.defaultTextEncodingName = "UTF-8"
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            a.settings.mixedContentMode = WebSettings.MIXED_CONTENT_ALWAYS_ALLOW
        }
        //处理https下加载http资源
    }
}